#!/bin/sh
# 安装管理Ant
App=ant
AppName=Ant
AppBase=/App
AppDir=$AppBase/$App
AppProg=$AppDir/bin/ant
AppSrcBase=/App/src
AppSrcFile=apache-ant-*.tar.*
AppSrcDir=$(find $AppSrcBase -maxdepth 1 -name "$AppSrcFile" -type f 2> /dev/null | sed -e 's/.tar.*$//' -e 's/^.\///' -e 's/-bin//')

RemoveFlag=0
InstallFlag=0

# 查询状态
fstatus()
{
    if [ ! -f "$AppProg" ]; then
            echo "$AppName 未安装"
    else
        echo "$AppName 已安装"
    fi
}

# 删除
fremove()
{
    RemoveFlag=1

    if [ -d "$AppDir" ]; then
        rm -rf $AppDir
        if [ $? -eq 0 ]; then
            echo "删除 $AppName"
        fi
    else
        echo "$AppName 未安装"
    fi
}

# 备份
fbackup()
{
    Day=$(date +%Y-%m-%d)
    BackupFile=$App-$Day.tgz

    if [ -f "$AppProg" ]; then
        cd $AppBase
        tar zcvf $BackupFile $App
        [ $? -eq 0 ] && echo "$AppName 备份成功" || echo "$AppName 备份失败"
    else
        echo "$AppName 未安装"
    fi
}

# 安装
finstall()
{
    InstallFlag=1

    test -f "$AppProg" && echo "$AppName 已安装"
    [ $? -ne 0 ] && fupdate
}

# 更新
fupdate()
{
    [ $RemoveFlag -ne 1 ] && fbackup
    test -f "$AppProg" && echo "$AppName 已安装"
    cd $AppSrcBase
    test -d "$AppSrcDir" && rm -rf $AppSrcDir

    tar jxf $AppSrcFile || tar zxf $AppSrcFile
    mv $AppSrcDir $AppDir

    if [ $? -eq 0 ]; then
        echo "$AppName 安装成功"
        grep -q "$AppDir" /etc/profile || echo "export PATH=$AppDir/bin:\$PATH" >> /etc/profile
    else
        echo "$AppName 安装失败"
        exit
    fi
}


ScriptDir=$(dirname $0)
ScriptFile=$(basename $0)
case "$1" in
    "install"   ) finstall;;
    "update"    ) fupdate;;
    "reinstall" ) fremove && finstall;;
    "remove"    ) fremove;;
    "backup"    ) fbackup;;
    "status"    ) fstatus;;
    *           )
    echo "$ScriptFile install              安装 $AppName"
    echo "$ScriptFile update               更新 $AppName"
    echo "$ScriptFile reinstall            重装 $AppName"
    echo "$ScriptFile remove               删除 $AppName"
    echo "$ScriptFile backup               备份 $AppName"
    echo "$ScriptFile status               查询 $AppName 状态"
    ;;
esac
